package com.ruoyi.common.utils.qrCode;

import com.google.common.base.Strings;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closer;
import com.ruoyi.common.core.domain.entity.DownloadFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName ZipUtil
 * @Description TODO
 * @Author luguanqing
 * @Date 2021/7/12 13:18
 * @Version 1.0
 */
public class ZipUtil {

    /**
     * 解压缩zip包
     *
     * @param zipFilePath        zip文件的全路径
     * @param unzipFilePath      解压后的文件保存的路径
     * @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含；false-不包含,目前只支持true
     * @param charset            The {@linkplain Charset charset} to be
     *                           used to decode the ZIP entry name and comment (ignored if
     *                           the <a href="package-summary.html#lang_encoding"> language
     *                           encoding bit</a> of the ZIP entry's general purpose bit
     *                           flag is set
     */
    public static List<String> unZip(String zipFilePath, String unzipFilePath, boolean includeZipFileName, Charset charset) throws IOException {
        List<String> filePaths = new ArrayList<>(32);
        if (Strings.isNullOrEmpty(zipFilePath)) {
            return filePaths;
        }
        File zipFile = new File(zipFilePath);
        // 如果解压后的文件保存路径包含压缩文件的文件名，则追加该文件名到解压路径
        String fileName = zipFile.getName();
        int pos;
        if (includeZipFileName) {
            pos = fileName.lastIndexOf(".");
            if (pos > 0) {
                fileName = fileName.substring(0, pos);
            }
            unzipFilePath = unzipFilePath + File.separator + fileName;
        }
        // 开始解压
        try (ZipFile zip = new ZipFile(zipFile, charset); Closer closer = Closer.create()) {
            for (Enumeration<? extends ZipEntry> zipEntries = zip.entries(); zipEntries.hasMoreElements(); ) {
                ZipEntry zipEntry = zipEntries.nextElement();
                if (zipEntry.isDirectory()) {
                    continue;
                }
                String zipEntryName = zipEntry.getName();
                String outPath = unzipFilePath + File.separator + zipEntryName;
                File outFile = new File(outPath);
                //目录不存在就创建吧
                com.google.common.io.Files.createParentDirs(outFile);
                BufferedInputStream bufferedIn = closer.register(new BufferedInputStream(zip.getInputStream(zipEntry)));
                BufferedOutputStream bufferedOut = closer.register(new BufferedOutputStream(new FileOutputStream(outFile)));
                ByteStreams.copy(bufferedIn, bufferedOut);
                filePaths.add(outPath.replace("\\", "/"));
            }
        }
        return filePaths;
    }

    /**
     * 解压，返回所有文件的路径
     *
     * @param zipFilePath        压缩包的路径
     * @param unZipFilePath      解压之后的目录
     * @param includeZipFileName 解压之后是否用压缩包名作为父目录
     * @return 返回文件的路径
     * @throws IOException I/O异常
     */
    public static List<String> unZip(String zipFilePath, String unZipFilePath, boolean includeZipFileName) throws IOException {
        Charset defaultCharset = Charset.forName("GBK");
        return unZip(zipFilePath, unZipFilePath, includeZipFileName, defaultCharset);
    }


    private static final int BUFFER_SIZE = 2 * 1024;

    public static void main(String[] args) throws FileNotFoundException {
        OutputStream out = new FileOutputStream(new File("D:\\121212\\121212.zip"));
        toZip("D:\\121212", out, true);
    }

    /**
     * 压缩成ZIP 方法1
     *
     * @param srcDir           压缩文件夹路径
     * @param out              压缩文件输出流
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 压缩成ZIP 方法2
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles, List<String> fileNames, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        int i = 0;
        try {
            zos = new ZipOutputStream(out);
            FileInputStream in=null;
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(fileNames.get(i)));
                i++;
                int len;
                try{
                    in = new FileInputStream(srcFile);
                    while ((len = in.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                    }
                }
                finally {
                    zos.closeEntry();
                    if(in!=null){
                        in.close();
                    }
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 压缩成ZIP 方法3
     * @param downloadFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip3(List<DownloadFile> downloadFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            InputStream in=null;
            for (DownloadFile downloadFile : downloadFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(downloadFile.getFileName()));
                int len;
                try{
                    in = downloadFile.getInputStream();
                    while ((len = in.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                    }
                }finally {
                    zos.closeEntry();
                    in.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        FileInputStream in=null;
        try {
            if (sourceFile.isFile()) {
                // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
                zos.putNextEntry(new ZipEntry(name));
                // copy文件到zip输出流中
                int len;
                in = new FileInputStream(sourceFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                // Complete the entry
                zos.closeEntry();
                in.close();
            } else {
                File[] listFiles = sourceFile.listFiles();
                if (listFiles == null || listFiles.length == 0) {
                    // 需要保留原来的文件结构时,需要对空文件夹进行处理
                    if (KeepDirStructure) {
                        // 空文件夹的处理
                        zos.putNextEntry(new ZipEntry(name + "/"));
                        // 没有文件，不需要文件的copy
                        zos.closeEntry();
                    }

                } else {
                    for (File file : listFiles) {
                        // 判断是否需要保留原来的文件结构
                        if (KeepDirStructure) {
                            // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                            // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                            compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                        } else {
                            compress(file, zos, file.getName(), KeepDirStructure);
                        }

                    }
                }
            }
        }finally {
            if(in !=null){
                in.close();
            }
        }
    }
}
